<?php

declare(strict_types=1);

namespace app\customer\service;

use app\customer\model\Customer as CustomerModel;

class Customer
{

    protected $return;
    protected $validate;
    public function __construct()
    {
        $this->validate = new \app\customer\validate\Customer();
        $this->return = [
            'code' => 500,
            'data' => [],
            'message' => ''
        ];
    }

    /**
     * @describe 获取客户列表
     * @author: Bobo
     * @date: 2024-06-05 18:02:26 
     * @param [] type
     * @return Renderable
     */
    public function getList(int $page = 1, int $limit = 10, array $where = [])
    {
        $return = $this->return;

        if (0 >= $page || 100 <= $limit) {
            // $return['message'] = 'Page or limit is invalid';
            return $return;
        }
        try {
            $total = CustomerModel::where($where)->count();

            if ($total <= 0) {
                $return['code'] = 0;
                // $return['message'] = 'No records found';
            } else {
                $list = CustomerModel::where($where)
                    ->page($page, $limit)
                    ->append(['creator_value', 'updater_value', 'owner_value', 'partner_value'])
                    ->select();

                $return['code'] = 0;
                $return['data'] = ['list' => $list, 'total' => $total];
            }
        } catch (\Throwable $th) {
            // $return['message'] = 'Failed to retrieve list. ' . $th->getMessage();
        }

        return $return;
    }

    /**
     * 获取客户详情
     * @param int $id 客户ID
     */
    public function getOneById(int $id)
    {
        $return = $this->return;
        if (empty($id) || !is_numeric($id)) return $return;
        $return['data'] = CustomerModel::find($id)->toArray();
        $return['code'] = 0;
        return $return;
    }


    /**
     * 创建客户
     * @param array $data 创建客户的数据
     */
    public function create($data)
    {
        try {
            if (!$this->validate->scene('create')->check($data)) {
                return ['code' => 100001, 'message' => $this->validate->getError()];
            }
            $exists = CustomerModel::where('is_del', 0)
                ->where(function ($query) use ($data) {
                    $query->where('email', $data['email'])
                        ->whereOr('phone', $data['phone']);
                })->find();
            if ($exists) {
                return ['code' => 200001, 'message' => '请检查手机号或邮箱'];
            }
            $res = CustomerModel::create($data);
            if ($res) {
                return ['code' => 0];
            } else {
                return ['code' => 300001];
            }
        } catch (\Throwable $th) {
            return ['code' => 300001, 'message' => '服务器内部错误：' . $th->getMessage()];
        }
    }

    /**
     * 更新客户
     * @param int $id 客户ID
     * @param array $data 更新客户的数据
     */
    public function update($data)
    {
        $res = CustomerModel::where('id', $data['id'])->find();
        if (!$res) {
            return false;
        }
        foreach ($data as $key => $value) {
            if ($res->$key != $value) {
                $res->$key = $value;
            }
        }

        // $exists = CustomerModel::where(function ($query) use ($data) {
        //     if (!empty($data['phone'])) {
        //         $query->where('phone', $data['phone']);
        //     }
        //     if (!empty($data['email'])) {
        //         $method = !empty($data['phone']) ? 'whereOr' : 'where';
        //         $query->$method('email', $data['email']);
        //     }
        //     $query->where('is_del', 0);
        // });
        // if ($exists) {
        //     return ['code' => 1, 'message' => '该客户已存在,请检查手机号或邮箱'];
        // }

        $result = $res->save();

        if ($result) {
            return ['code' => 0, 'message' => '操作成功'];
        } else {
            return ['code' => 1, 'message' => '操作失败'];
        }
    }

    /**
     * 删除客户
     * @param int $id 客户ID
     */
    public function delete($id)
    {
        return CustomerModel::where('id', $id)->delete();
    }

    /**
     * @describe 批量逻辑删除客户
     * @author: Bobo
     * @date: 2024-06-26 14:53:00 
     * @param [arr] @required $ids 客户ID数组
     * @return Renderable
     */
    public function batchLogicalDelete($ids)
    {
        return CustomerModel::where('id', 'in', $ids)->update(['is_del' => time()]);
    }

    /**
     * @describe 批量修改客户
     * @author: Bobo
     * @date: 2024-07-06 14:53:00 
     * @param [arr] @required $condition 条件
     * @param [arr] @required $update 数据
     * @return Renderable
     */
    public function batchUpdate(array $condition, array $update)
    {
        $return = [
            'code' => 500,
            'message' => 'success'
        ];
        if (empty($condition) || empty($update)) {
            $return['message'] = 'Condition and update arguments must not be empty.';
        } else {
            try {
                CustomerModel::where($condition)->update($update);
                $return['code'] = 0;
            } catch (\Throwable $th) {
                $return['message'] = 'Batch update failed. ' . $th->getMessage();
            }
        }
        return $return;
    }
}
